#!/usr/bin/python

#Created by turk 2016-06-03
#SSH TOOL [PYTHON]
#Version 1.0 

import sys
import pexpect
import getpass, os
import re
import time
import logging

LOGFILE = '/home/bsmp/work/log/stormssh.log'

#Logger
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',  
                    datefmt='%Y-%m-%d %H:%M:%S',  
                    filename=LOGFILE,  
                    filemode='w')  
console = logging.StreamHandler()  
console.setLevel(logging.DEBUG)  
# set print format
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')  
console.setFormatter(formatter)  
#
logging.getLogger('').addHandler(console)  
logger = logging.getLogger('test.delay')    


#putfile = '/home/B002/appproto_lib/appproto.etxt'
#dstdir = '/home/bsmp/dpi_flow_parser_v1.01/config/'



def ssh_command (user, host, password, command):
    passwd_key = '.*assword.*'  
    ssh_newkey = 'continue connecting'
    cmd = 'ssh -l %s %s "%s"'%(user, host, command)
    logger.debug('cmd:%s'%(cmd) )  
    child = pexpect.spawn(cmd)
    
    i = child.expect([pexpect.TIMEOUT, passwd_key],2)
        #logger.debug( 'expect i %d '%(i) )   
    if i == 1 :
        child.sendline(password)
        logger.info('[%s] send password'%(host))
    elif i == 0:
        i = child.expect([pexpect.TIMEOUT, ssh_newkey],2)
        logger.info('[%s] send password auth'%(host))
        if i == 1:
            child.sendline('yes')
            i = child.expect([pexpect.TIMEOUT, passwd_key],2)
            child.sendline(password)
            
    logger.info('[%s] login success'%(host))     
    logger.info('[%s] exec commod-%s'%(host,command))  
            #logger.debug( 'expect i %d '%(i) )   
    child.expect(pexpect.EOF,60)  
    r = child.before 
    logger.info('[%s] %s'%(host,r))
    child.close()
    logger.info('%s ssh success.'%(host) )

def main ():
    print sys.argv,len(sys.argv)
    if len(sys.argv) <> 5:
        print "Usage:<HOSTFILE> <USERNAME> <PASSWORD> <COMMAND>"
        return
    
    HOSTLIST = sys.argv[1]
    user=sys.argv[2]
    passwd=sys.argv[3]
    command=sys.argv[4]
    
    logger.debug('scp starting ...')
    
    f = open(HOSTLIST, "r")  
    while True:  
        line = f.readline()  
        hostname = line.strip('\n')
        if hostname:  
            ssh_command(user, hostname,  passwd, command)
            print 'hostname %s'%(hostname)  
        else:  
            break
    f.close()  
    
    
    
    #ltime = time.time()
    #ftime = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
    #bak_name = putfile + '_' + ftime
    #os.rename(putfile, bak_name)

    logger.debug('scp end ...')
    return

if __name__ == '__main__':
    # do the UNIX double-fork magic, see Stevens' "Advanced 
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    # decouple from parent environment
    #os.chdir("/home/B002/appproto_lib") 
    # start the daemon main loop
    try:
        main()
    except Exception, e:
        print str(e)
        #traceback.print_exc()
        os._exit(1)

